import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 一级路由
  { path: '/detail/:id', component: () => import('@/views/Detail.vue') },
  { path: '/login', component: () => import('@/views/Login.vue') },
  { path: '/register', component: () => import('@/views/Register.vue') },
  {
    path: '/',
    component: () => import('@/views/Home.vue'),
    children: [
      { path: 'article', component: () => import('@/views/Layout/Article.vue') },
      { path: 'collect', component: () => import('@/views/Layout/Collect.vue') },
      { path: 'like', component: () => import('@/views/Layout/Like.vue') },
      { path: 'user', component: () => import('@/views/Layout/User.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 允许访问的列表
const allow = ['/login', '/register', '/xxx', '/yyyy']
// 添加全局前置导航守卫
router.beforeEach((to, from, next) => {
  if (allow.includes(to.path)) {
    next()
  } else {
    // 说明访问的不是登录、不是注册，还要判断本地存储是否有token
    if (localStorage.getItem('mobile-token')) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
